using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using WebapiTemplate.Application.Common.Interface;
using WebapiTemplate.Domain.Entity;
using WebapiTemplate.Infrastructure.Persistence;

/// <summary>
/// 此类是生成种子数据类，若表无数据则会自动为表添加一条初始数据
/// </summary>
namespace WebapiTemplate.Infrastructure
{
    public static class ApplicationStartupExtensions
    {
        public static async void MigrateDatabase(this WebApplication app)//using Microsoft.AspNetCore.Builder;
        {
            using var scope = app.Services.CreateScope();//using Microsoft.Extensions.DependencyInjection;
            var services = scope.ServiceProvider;

            try
            {
                var context = services.GetRequiredService<WebapiDbcontext>();
                
                // 自动同步迁移文件到数据库服务器，前提是必须先（手动）生成迁移文件
                context.Database.Migrate();//using WebapiTemplate.Domain.Entity;//需要该项目引用<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.6" />

                var UserRes=services.GetRequiredService<IRepository<User>>();
                var RoleRes=services.GetRequiredService<IRepository<Role>>();
                var UserRoleRes=services.GetRequiredService<IRepository<UserRole>>();

                // 如果没有任何角色，则生成种子数据
                if(!UserRoleRes.Table.Any())
                {
                    var role=new Role{
                        Rolename="超级管理员"
                    };
                    var user=new User{
                        Username="admin",
                        Password="113"
                    };
                    await RoleRes.AddAsync(role);
                    await UserRes.AddAsync(user);
                    await UserRoleRes.AddAsync(new UserRole{
                        RoleId=role.Id,
                        UserId=user.Id
                    });
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"An error occurred migrating the DB: {ex.Message}");
            }
        }
    }
}